package cn.yy.cloudpay.util;

import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import cn.yy.cloudpay.R;
import cn.yy.pos.launcher.service.Operator;

public class PrinterStringUtil {

	private Context mContext;
	private Operator operator;
	public static final int MERCHANT_COPY = 1; // 商户存根
	public static final int CUSTOMER_COPY = 2; // 客户存根
	
	public PrinterStringUtil(Context context,Operator operator) {
		this.mContext = context;
		this.operator = operator;
	}
	
	private String getString(int resId) {
		return mContext.getString(resId);
	}
	
	// 获取支付宝或微信的打印数据
	public byte[] getPrintString(String string,int type,Integer paytype, Integer opType) throws JSONException, UnsupportedEncodingException {
		byte[] printData = null;
		switch(opType){
		case Constant.KEYBOARD_OP_TYPE_PAY: // 支付
			printData = getPayPrintString(string,type,paytype).getBytes(getString(R.string.print_encoding));
			break;
		case Constant.KEYBOARD_OP_TYPE_RETURN: // 退款
			printData = getRetundPrintString(string,type,paytype).getBytes(getString(R.string.print_encoding));
			break;
		}
		return printData;
	}
	
	public String getPayPrintString(String string,int type,Integer paytype) throws JSONException {
		StringBuffer scriptBuffer = new StringBuffer();
//		String printPage = operator.getPrintPage();
//		if(!"2".equals(printPage)  && type == CUSTOMER_COPY){ // 只打印一联，即商户存根
//			scriptBuffer.append(getPrintString(string,MERCHANT_COPY, paytype));
//			return scriptBuffer.toString();
//		}
		
		JSONObject json = new JSONObject(string);
		
		scriptBuffer.append(getString(R.string.print_setTextLarge));// 设置标题字体为大号
		scriptBuffer.append("!yspace 20\n");// 设置行间距20 ,取值【0,60】，默认6
		scriptBuffer.append("*text c 支付凭条 \n"); //标题大号居中字体
		scriptBuffer.append(getString(R.string.print_setTextNormal));// 设置内容字体为中号
		scriptBuffer.append("!yspace 10\n");// 设置内容行间距10
		scriptBuffer.append("*line\n");// 打印虚线
		
		if(type == MERCHANT_COPY) {
			scriptBuffer.append("*text l 商户存根/MERCHANT_COPY \n");
		} else {
			scriptBuffer.append("*text l 持卡人存根/CUSTOMER_COPY \n");
		}
		scriptBuffer.append("*line\n");// 打印虚线

		String trade_no = getJsonStr(json,"outTradeNo");
		if(StringUtil.isEmpty(trade_no)){
			trade_no = getJsonStr(json,"outtradeno");
		}

		//门店名称
		scriptBuffer.append("*text l 商户名称："+operator.getTenantsName()+getString(R.string.print_changeLine));
		scriptBuffer.append("*text l 门店编号："+operator.getTenantsID()+getString(R.string.print_changeLine));
		scriptBuffer.append("*text l 终端编号："+operator.getPosCode()+getString(R.string.print_changeLine));
		scriptBuffer.append("*text l 流水号："+ trade_no + getString(R.string.print_changeLine));
		scriptBuffer.append("*line" + "\n");// 打印虚线
		
		String totalFee = "", cashFee = "",coupon_fee="";

		scriptBuffer.append("*text l 支付渠道：" + Constant.PAY_TYPE_MAP.get(paytype) + getString(R.string.print_changeLine));
		if(Constant.PAY_TYPE_MICROPAY.equals(paytype)){
			//买家用户标识
			scriptBuffer.append("*text l 支付账户："+getJsonStr(json,"openid")+getString(R.string.print_changeLine));
			//微信平台交易号
			scriptBuffer.append("*text l NO."+getJsonStr(json,"transactionID")+getString(R.string.print_changeLine));
			totalFee = getCurrencyFormat(getJsonStr(json,"totalFee"));
			cashFee = getCurrencyFormat(getJsonStr(json,"cashFee"));
			if(!StringUtil.isEmpty(getJsonStr(json,"coupon_fee"))){
				coupon_fee = getCurrencyFormat(getJsonStr(json,"coupon_fee"));
			}
		}else if(Constant.PAY_TYPE_ALIPAY.equals(paytype)){
			//买家用户标识
			scriptBuffer.append("*text l 支付账户："+getJsonStr(json,"buyerLogonId")+getString(R.string.print_changeLine));
			//支付宝平台交易号
			scriptBuffer.append("*text l NO."+getJsonStr(json,"tradeNo")+getString(R.string.print_changeLine));
			totalFee = getJsonStr(json,"totalAmount");
			cashFee = getJsonStr(json,"totalAmount");
		}else{
			totalFee = getJsonStr(json,"amt");
			cashFee = getJsonStr(json,"money");
		}
		
		scriptBuffer.append("!qrcode 150 2\n ");
		scriptBuffer.append("*qrcode c "+trade_no+"\n");
		
		scriptBuffer.append("*line\n");// 打印虚线
		
		//交易金额
		scriptBuffer.append("*text l 交易金额："+totalFee+"元"+getString(R.string.print_changeLine));
		//实收金额
		scriptBuffer.append("*text l 实收金额："+cashFee+"元"+getString(R.string.print_changeLine));

		if(!StringUtil.isEmpty(coupon_fee)){
			scriptBuffer.append("*text l 代金券金额："+coupon_fee+"元"+getString(R.string.print_changeLine));
		}

		scriptBuffer.append("*line" + "\n");// 打印虚线
		//操作员姓名
//		scriptBuffer.append("*text l 操作员："+operator.getOperatorName()+getString(R.string.print_changeLine));//
		//日期时间 getTimeEnd(getJsonStr(json,"timeEnd"))
		scriptBuffer.append("*text l 柜员号："+operator.getOperatorAccount()+getString(R.string.print_changeLine));
		scriptBuffer.append("*text l 时间："+getTimeEnd()+"\n");
		scriptBuffer.append("*text l 持卡人签名： \n");
		scriptBuffer.append("*feedline 2\n");
		scriptBuffer.append("*line" + "\n");// 打印虚线
		scriptBuffer.append("*text l ※如需退货需凭此小票及小票上的二维码，请保留小票\n");
//		scriptBuffer.append("*text l 本人确认以上交易，同意将其记入本卡账户\n");
		String servicePhone = operator.getServicePhone();
		if(!StringUtil.isEmpty(servicePhone)){
			scriptBuffer.append("*text l 服务热线："+servicePhone+getString(R.string.print_changeLine));
		}
//		scriptBuffer.append(getString(R.string.print_cut_line)); //裁剪线
//		if(type == CUSTOMER_COPY) { // 打印商户存根
//			scriptBuffer.append("*feedline 2\n");
//			scriptBuffer.append(getPrintString(string,MERCHANT_COPY, paytype));
//		}else{
//			
//		}
		scriptBuffer.append("*feedline 2\n");
		return scriptBuffer.toString();
	}
	
	public String getRetundPrintString(String string,int type,Integer paytype) throws JSONException {
		StringBuffer scriptBuffer = new StringBuffer();
//		String printPage = operator.getPrintPage();
//		if(!"2".equals(printPage)  && type == CUSTOMER_COPY){ // 只打印一联，即商户存根
//			scriptBuffer.append(getRetundPrintString(string,MERCHANT_COPY, paytype));
//			return scriptBuffer.toString();
//		}
		
		JSONObject json = new JSONObject(string);
		
		String buyer = ""; // 买家用户标识
		String totalFee = ""; // 退款金额
		String cashFee = ""; // 实退金额
		String tradeNo = ""; // 平台交易号
		String outTradeNo = ""; // 流水号
		
		if(Constant.PAY_TYPE_MICROPAY.equals(paytype)){
			buyer = getJsonStr(json,"openid");
			tradeNo = getJsonStr(json,"transaction_id");
			totalFee = getCurrencyFormat(getJsonStr(json,"refund_fee"));
			cashFee = getCurrencyFormat(getJsonStr(json,"refund_fee"));
			outTradeNo = getJsonStr(json,"out_refund_no");
		}else if(Constant.PAY_TYPE_ALIPAY.equals(paytype)){
			buyer = getJsonStr(json,"buyerLogonId");
			tradeNo = getJsonStr(json,"tradeNo");
			totalFee = getJsonStr(json,"refundFee");
			cashFee = getJsonStr(json,"refundFee");
			outTradeNo = getJsonStr(json,"outTradeNo");
		} else{
			buyer = getJsonStr(json,"buyerlogonid");
			tradeNo = getJsonStr(json,"terminalseq");
			totalFee = getJsonStr(json,"amt");
			cashFee = getJsonStr(json,"amt");
			outTradeNo = getJsonStr(json,"outtradeno");
		}
		
		scriptBuffer.append(getString(R.string.print_setTextLarge));// 设置标题字体为大号
		scriptBuffer.append("!yspace 20\n");// 设置行间距20 ,取值【0,60】，默认6
		scriptBuffer.append("*text c 退款凭条 \n"); //标题大号居中字体
		scriptBuffer.append(getString(R.string.print_setTextNormal));// 设置内容字体为中号
		scriptBuffer.append("!yspace 10\n");// 设置内容行间距10
		scriptBuffer.append("*line\n");// 打印虚线
		
		if(type == MERCHANT_COPY) {
			scriptBuffer.append("*text l 商户存根/MERCHANT_COPY \n");
		} else {
			scriptBuffer.append("*text l 持卡人存根/CUSTOMER_COPY \n");
		}
		scriptBuffer.append("*line\n");// 打印虚线
		
		//门店名称
		scriptBuffer.append("*text l 商户名称："+operator.getTenantsName()+getString(R.string.print_changeLine));
		scriptBuffer.append("*text l 门店编号："+operator.getTenantsID()+getString(R.string.print_changeLine));
		scriptBuffer.append("*text l 终端编号："+operator.getPosCode()+getString(R.string.print_changeLine));
		scriptBuffer.append("*text l 流水号："+ outTradeNo + getString(R.string.print_changeLine));
		scriptBuffer.append("*line" + "\n");// 打印虚线
		
		scriptBuffer.append("*text l 支付渠道：" + Constant.PAY_TYPE_MAP.get(paytype) + getString(R.string.print_changeLine));
		//买家用户标识
		scriptBuffer.append("*text l 支付账户："+buyer+getString(R.string.print_changeLine));
		//支付宝平台交易号
		scriptBuffer.append("*text l NO."+tradeNo+getString(R.string.print_changeLine));
		scriptBuffer.append("*line\n");// 打印虚线
		
//		printerInterfaceImpl.printScript(scriptBuffer.toString());
//		scriptBuffer.delete(0, scriptBuffer.length());
		//交易金额
		scriptBuffer.append("*text l 退款金额：-"+totalFee+"元"+getString(R.string.print_changeLine));
		//实收金额
		scriptBuffer.append("*text l 实退金额：-"+cashFee+"元"+getString(R.string.print_changeLine));

		scriptBuffer.append("*line" + "\n");// 打印虚线
		//操作员姓名
//		scriptBuffer.append("*text l 操作员："+operator.getOperatorName()+getString(R.string.print_changeLine));//
		//日期时间 getTimeEnd(getJsonStr(json,"timeEnd"))
		scriptBuffer.append("*text l 柜员号："+operator.getOperatorAccount()+getString(R.string.print_changeLine));
		scriptBuffer.append("*text l 时间："+getTimeEnd()+"\n");
		scriptBuffer.append("*text l 持卡人签名： \n");
		scriptBuffer.append("*feedline 2\n");
		scriptBuffer.append("*line" + "\n");// 打印虚线
		String servicePhone = operator.getServicePhone();
		if(!StringUtil.isEmpty(servicePhone)){
			scriptBuffer.append("*text l 服务热线："+servicePhone+getString(R.string.print_changeLine));
		}
		scriptBuffer.append(getString(R.string.print_cut_line)); //裁剪线
//		printerInterfaceImpl.printScript(scriptBuffer.toString());
//		if(type == CUSTOMER_COPY) { // 打印商户存根
//			scriptBuffer.append("*feedline 2\n");
//			scriptBuffer.append(getRetundPrintString(string,MERCHANT_COPY, paytype));
//		}
		scriptBuffer.append("*feedline 2\n");
		return scriptBuffer.toString();
	}
	
	private String getJsonStr(JSONObject json, String name ){
		try{
			return json.getString(name);
		}catch(Exception e){
			e.printStackTrace();
			return "";
		}
	}
	
	
	/**
	 * 货币格式化
	 * @param string
	 * @return
	 */
	private String getCurrencyFormat(String string) {
//		NumberFormat format = NumberFormat.getCurrencyInstance(Locale.CHINA);
//		return format.format(Double.parseDouble(string)*0.01);
		return String.format("%.2f", Float.valueOf(string)*0.01f);
	}
	
	private String getTimeEnd() throws JSONException {
//		JSONObject json = new JSONObject(string);
//		long time = json.getLong("time");
//		Date date = new Date(time);
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		return format.format(date);
	}
}
